<?php

$db = new Database();
$auth = Auth::getAuth('current_user');
if (Auth::hasAuth('current_user')) {
    $tblName = $_POST['tableName'];
    $TrackNo = $_POST['trackingNumber'];
    $user_id = $auth['id'];
//     $tblName = "1_tbl_overtimerequestform";
//     $TrackNo = "OTForm0107";
    
    if (isset($tblName) && isset($TrackNo)) {
        $sql = "SELECT frm.ID as frm_id, ws.id, ws.form_name as formName,ws.id as formId, frm.Requestor as requestorId ,
            CONCAT_WS(' ',u.first_name,u.last_name) as requestor, u.extension as requestor_extension, frm.Status as status,frm.DateCreated as dateSubmitted, frm.DateUpdated as dateUpdated,
            frm.*,frm.LastAction as actions, CASE WHEN
            EXISTS(SELECT * FROM tbstarred WHERE tablename = {$db->escape($tblName)} AND data_id = frm.id AND user_id = {$db->escape($user_id)}) THEN '1'
            ELSE
            '0'
            END AS is_starred FROM $tblName frm LEFT JOIN tbuser u ON frm.Requestor = u.id, 
            tb_workspace ws WHERE frm.TrackNo = {$db->escape($TrackNo)}  AND ws.form_table_name = {$db->escape($tblName)}";
        //echo $sql;
        $getRequest = $db->query($sql, "row");
        
        //for action
        $json_action = json_decode($getRequest['actions']);
        $json_toMobility = array();
        foreach ($json_action as $key => $value) {
            $array2 = array("label" => $json_action->{$key}->{"button_name"},
                "action" => $json_action->{$key}->{"child_id"});
            array_push($json_toMobility, $array2);
            // echo $json_action->{$key}->{"button_name"};
            // echo $json_action->{$key}->{"child_id"};
        }

        //get requestor image
        $userImage = "";
        if($getRequest['requestor_extension']!=""){
            $encryptID =  md5(md5($getRequest['requestorId']));
            $path = $encryptID."."."/small_".$encryptID.".".$getRequest['requestor_extension'];
            $userImage = "/images/formalistics/tbuser/".$path;
        }
        
        $json = array("formName" => $getRequest['formName'],
            "formId" => $getRequest['formId'],
            "ID" => $getRequest['frm_id'],
            "trackingNumber" => $getRequest['TrackNo'],
            "requestorId" => $getRequest['requestorId'],
            "processorId" => $getRequest['Processor'],
            "requestor" => $getRequest['requestor'],
            "requestorImageLink" => $getRequest['requestor'],
            "status" => $getRequest['status'],
            "is_starred" => $getRequest['is_starred'],
            "requestor_image" => $userImage,
            "dateSubmitted" => $getRequest['dateSubmitted'],
			"dateUpdated" => $getRequest['dateUpdated'],
            "fields" => $getRequest,
            "actions" => $json_toMobility);


        echo json_encode($json);
    } else {
        $json = array("STATUS" => "ERROR");
        echo json_encode($json);
    }
}